package com.doge.calcalbum.business.sysalbum

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.core.view.setPadding
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.doge.calcalbum.R
import com.doge.calcalbum.analysis.*
import com.doge.calcalbum.analysis.analysisEvent
import com.doge.calcalbum.business.ITEM_CHECK
import com.doge.calcalbum.business.album.AlbumRepository
import com.doge.calcalbum.business.vip.AppVipViewModel
import com.doge.calcalbum.business.guide.GuideAlbum3Layout
import com.doge.calcalbum.business.vip.VipHelper
import com.doge.calcalbum.core.BaseActivity
import com.doge.calcalbum.core.PermissionUtil
import com.doge.calcalbum.core.base.LoadStatus
import com.doge.calcalbum.core.base.adapters.ITEM_CLICKED
import com.doge.calcalbum.core.base.adapters.ITEM_LONG_CLICKED
import com.doge.calcalbum.core.base.appViewModels
import com.doge.calcalbum.core.base.isRefreshing
import com.doge.calcalbum.databinding.ActivitySysAlbumBinding
import com.doge.calcalbum.db.model.Album
import com.doge.calcalbum.utils.*
import com.doge.calcalbum.widgets.GridItemDecoration

class SysAlbumActivity : BaseActivity() {
    private val binding by lazy { ActivitySysAlbumBinding.inflate(layoutInflater) }
    private val albumId by lazy { intent.getIntExtra(EXTRA_ALBUM_ID, Album.DEFAULT_PICTURE_ID) }
    private val albumType by lazy { intent.getIntExtra(EXTRA_ALBUM_TYPE, Album.TYPE_PICTURE) }
    private val viewModel by viewModels<SysAlbumViewModel> { SysAlbumViewModelFactory(albumId, albumType) }
    private val vipViewModel by appViewModels<AppVipViewModel>()
    private val adapter by lazy { SysEntryAdapter() }
    private var limitCount = 0
    private var hasUploaded = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        analysisEvent(page_sys_album)
        systemWindowInsetsTop.observe(this) {
            binding.fitsSys.setPadding(it / 2)
        }
        binding.pageBack.setOnClickCallback { finish() }
        binding.upload.setOnClickCallback { upload() }
        binding.recyclerView.itemAnimator = null
        val itemDecoration = object : GridItemDecoration(2.dp, Color.TRANSPARENT) {
            override fun getItemSidesIsHaveOffsets(itemPosition: Int) =
                arrayOf(itemPosition % 4 != 0, true, itemPosition % 4 != 3, true)
        }
        binding.recyclerView.addItemDecoration(itemDecoration)
        binding.recyclerView.layoutManager = GridLayoutManager(binding.recyclerView.context, 4)
        binding.recyclerView.adapter = adapter
        adapter.setListener(::handleAdapterCallback)
        when (albumType) {
            Album.TYPE_PICTURE -> {
                viewModel.initPictureLoading.observe(this) {
                    binding.loading.isVisible = it.isRefreshing()
                }
                viewModel.pictureList.observe(this) {
                    binding.empty.isVisible = it.isNullOrEmpty()
                    adapter.submitList(it)
                }
            }
            Album.TYPE_VIDEO -> {
                viewModel.initVideoLoading.observe(this) {
                    binding.loading.isVisible = it.isRefreshing()
                }
                viewModel.videoList.observe(this) {
                    binding.empty.isVisible = it.isNullOrEmpty()
                    adapter.submitList(it)
                }
            }
        }
        when (albumType) {
            Album.TYPE_VIDEO -> vipViewModel.limitVideoCount.observe(this) { limitCount = it }
            Album.TYPE_PICTURE -> vipViewModel.limitPictureCount.observe(this) { limitCount = it }
        }

        viewModel.copyLoading.observe(this) {
            if (it.isRefreshing()) {
                binding.loadingUpload.isVisible = true
                binding.upload.alpha = 0.5f
            } else if (it == LoadStatus.SUCCESS) {
                toast(R.string.upload_completed)
                finish()

                when (albumType) {
                    Album.TYPE_PICTURE -> asyncAnalysisEvent {"${insert_picture}_${AlbumRepository.get().totalCount(albumType)}" }
                    Album.TYPE_VIDEO -> asyncAnalysisEvent {"${insert_video}_${AlbumRepository.get().totalCount(albumType)}" }
                }

                VipHelper.tryShowWhenUploadFileFirstTime(albumType)
            }
        }
        SysAlbumRepository.get().refresh()

        GuideAlbum3Layout.attach(binding.root)
    }

    override fun onResume() {
        super.onResume()
        vipViewModel.refreshLimitCount()
    }

    private fun handleAdapterCallback(action: String, item: Any?) {
        when (action) {
            ITEM_CLICKED, ITEM_LONG_CLICKED, ITEM_CHECK -> {
                adapter.switch(item as? SysEntry?)
                val selectedCount = adapter.selected.size
                if (selectedCount > limitCount) {
                    adapter.switch((item as? SysEntry?)?.copy(selected = true))
                    toast(R.string.vip_limit)
                    VipHelper.showBuyDialog("limit${limitCount}", this)
                }
            }
        }
    }

    private fun upload() {
        if (hasUploaded) return
        hasUploaded = true
        val selected = adapter.selected
        if (selected.isEmpty()) {
            toast(R.string.please_select_entry)
            hasUploaded = false
        } else {
            SysEntryDeleteHelper.requireCheckDelete(this) {
                viewModel.copyToAlbum(selected, it)
                hasUploaded = false
            }
        }
    }

    companion object {
        private const val EXTRA_ALBUM_TYPE = "albumType"
        private const val EXTRA_ALBUM_ID = "albumId"
        fun start(context: FragmentActivity?, albumId: Int?, albumType: Int?) {
            if (context == null || albumId == null || albumType == null) return

            PermissionUtil.requestPermissions(context.lifecycle, android.Manifest.permission.READ_EXTERNAL_STORAGE,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE) {
                if (it) {
                    context.startActivity(Intent(context, SysAlbumActivity::class.java).apply {
                        putExtra(EXTRA_ALBUM_ID, albumId)
                        putExtra(EXTRA_ALBUM_TYPE, albumType)
                    })
                }
            }
        }
    }
}